package cn.dlc.com.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 
 * Copyright:Copyright (c) 2020
 *
 * @Description: reids锁，通过setnx命令实现锁。，不需要一直try了，
 *
 * @Version: v1.0.0
 * @author: 立川
 * @date: 2020年8月26日-下午3:55:15
 */
@Component
public class RedisLock implements Lock{
	
	private final String LOCK_NAME = "lock_name";
	
	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public void lock() {
		while(true) {
			// 这个就是对于的setnx方法
//			Boolean result = redisTemplate.opsForValue().setIfAbsent("lockName", LOCK_NAME);
			Boolean result = redisTemplate.opsForValue().setIfAbsent("lockName", LOCK_NAME, 15, TimeUnit.SECONDS);
			if(result) {
				return ;
			} else {
				System.out.println("waiting......");
			}
		}
	}
	
	@Override
	public void unlock() {
		// 释放锁
		redisTemplate.delete("lockName");
	}
	
	
	
	@Override
	public boolean tryLock() {
		return false;
	}
	
	@Override
	public void lockInterruptibly() throws InterruptedException {
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return false;
	}

	@Override
	public Condition newCondition() {
		return null;
	}

}
